package com.rzico.quartz.job;

import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Supplier;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.SupplierService;
import com.rzico.core.entity.SysJob;
import com.rzico.core.service.SysJobService;
import com.rzico.market.entity.MarketOrderApply;
import com.rzico.market.service.MarketOrderApplyItemService;
import com.rzico.market.service.MarketOrderApplyService;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.AskforStatusEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.enumx.ShippingStatusEnum;
import com.rzico.order.service.*;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 京东订单开票信息同步
 */
public class JDOrderInvoiceTask implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    protected OrderService orderService;

    @Autowired
    protected AskforService askforService;

    @Autowired
    protected AskforItemService askforItemService;

    @Autowired
    protected ShippingService shippingService;

    @Autowired
    protected ShippingItemService shippingItemService;

    @Autowired
    protected MarketOrderApplyService marketOrderApplyService;

    @Autowired
    protected MarketOrderApplyItemService marketOrderApplyItemService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        try {
            if (sysJob.getExecStatus().equals(1)) {
                //不能重复执行
                return;
            }
            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            // 这里开始
            /**
             * 获取当前商户的信息
             */
            String mchId = "";
            Long enterpriseId = 0L;
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("name","葫芦派");
            List<Enterprise> enterpriseList= enterpriseService.selectList(param);
            if (0 < enterpriseList.size()) {
                mchId = enterpriseList.get(0).getMchId();
                enterpriseId = enterpriseList.get(0).getId();
            }
            //获取京东供应商id
            Long supplierId = 0L;
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("name","京东");
            List<Supplier> supplierList = supplierService.selectList(params);
            if (0 < supplierList.size()) {
                supplierId = supplierList.get(0).getId();
            }
            //查询京东供应商所有送货单
            Map<String,Object> shipParams = new HashMap<>();
            shipParams.put("supplierId", supplierId);
            List<Shipping> shipList = shippingService.selectList(shipParams);
            List<ShippingItem> allShippingItemList = new ArrayList<ShippingItem>();//所有发货单项信息
            //所有待保存的发货单项信息,因为发货单会根据商品进行拆分，京东订单亦是如此，京东子订单中可能包含多件商品，避免出现重复的子订单，京东子订单开票时必须不可重复
            List<ShippingItem> addShippingItemList = new ArrayList<ShippingItem>();
            List<String> allJdOrderIdList = new ArrayList<String>();
            //根据所有发货单获取所有发货单项
            /**
             * 先查询发货状态为发货完成的京东发货单，再通过发货单的order_id查询订单状态，取订单状态为完成、评价的订单或发货单创建时间已超过七天
             * 判断本订单是否有京东商品退货申请，若无退货申请、申请完成或申请取消的话则对订单下的所有商品进项录入，退货申请单状态在进行中不进项录入
             * 将待录入的订单信息汇总并保存
             */
            for (Shipping shipping : shipList) {
                if (ShippingStatusEnum.SHIPPING_STATUS_RECEIVED.getId().equals(shipping.getShippingStatus()) || ShippingStatusEnum.SHIPPING_STATUS_COMPLETE.getId().equals(shipping.getShippingStatus())) {
                    Order order = orderService.selectByPrimaryKey(shipping.getOrderId());
                    if (OrderStatusEnum.ORDER_STATUS_COMPLETE.getId().equals(order.getOrderStatus())
                            || OrderStatusEnum.ORDER_STATUS_REVIEWED.getId().equals(order.getOrderStatus())
                            || 0 < new Date().compareTo(DateUtils.addDays(shipping.getCreateDate(),+7))) {
                        //查询来源订单是否有退货申请
                        List<ShippingItem> shippingItemList = shippingItemService.getItemList(shipping.getId());
                        boolean askforing = false;//是否有正在进行中的退货申请,无：false,有：true
                        List<ShippingItem> removeShippingItemList = new ArrayList<ShippingItem>();//若产生退货时的退货商品单项--系统商品进行退货数量全退无部分退
                        Map<String, Object> askforParam = new HashMap<String, Object>();
                        askforParam.put("orderId", order.getId());
                        List<Askfor> askforList = askforService.selectList(askforParam);
                        for (Askfor askfor : askforList) {
                            if (!(askfor.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_COMPLETE.getId()) || askfor.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_CANCLEED.getId()))) {
                                askforing = true;
                                continue;
                            }
                            //若此申退货申请单已完成，说明商品产生退货且数量全退
                            List<AskforItem> askforItemList = askforItemService.getItemList(askfor.getId());
                            for (ShippingItem si : shippingItemList) {
                                for (AskforItem ai : askforItemList){
                                    if (si.getSn().equals(ai.getSn())) {
                                        removeShippingItemList.add(si);
                                    }
                                }
                            }
                        }
                        if (askforing) {
                            continue;
                        }
                        allShippingItemList.addAll(shippingItemList);
                        if (0 < removeShippingItemList.size()) {
                            allShippingItemList.removeAll(removeShippingItemList);
                        }
                    }
                }
            }
            //去除重复的京东子订单好
            for (ShippingItem shippingItem : allShippingItemList){
                if (!allJdOrderIdList.contains(shippingItem.getSubTranSn())){
                    allJdOrderIdList.add(shippingItem.getSubTranSn());
                    addShippingItemList.add(shippingItem);
                }
            }
            Map<String,Object> marketOrderApplyParams = new HashMap<>();
            marketOrderApplyParams.put("supplierId", supplierId);
            List<String> shippingItemJdorderIdList = marketOrderApplyService.selectAlljdorderIdList(marketOrderApplyParams);
            //去除数据库已保存的子订单
            List<ShippingItem> finalAddShippingItemList = new ArrayList<ShippingItem>();
            for (ShippingItem shippingItem : addShippingItemList) {
                if (!shippingItemJdorderIdList.contains(shippingItem.getSubTranSn())) {
                    finalAddShippingItemList.add(shippingItem);
                }
            }
            if (0 < finalAddShippingItemList.size()) {
                String token = JDServiceUtils.refrash_token();
                //逐条保存待录入订单信息汇总
                for (ShippingItem shippingItem : finalAddShippingItemList) {
                    Shipping shipping = shippingService.selectByPrimaryKey(shippingItem.getShippingId());
                    Order order = orderService.selectByPrimaryKey(shipping.getOrderId());
                    Map<String, Object> orderApplyMap = new HashMap<String, Object>();
                    orderApplyMap.put("order_id", order.getId());
                    orderApplyMap.put("order_sn", order.getSn());
                    orderApplyMap.put("order_create_date", order.getCreateDate());
                    orderApplyMap.put("shipping_id", shipping.getId());
                    orderApplyMap.put("shipping_sn", shipping.getSn());
                    orderApplyMap.put("shipping_send_date", shipping.getCreateDate());
                    orderApplyMap.put("shipping_item_id", shippingItem.getId());
                    orderApplyMap.put("jd_parent_order", shipping.getTranSn());
                    orderApplyMap.put("jd_order", shippingItem.getSubTranSn());
                    //查询京东订单信息：获取结算价格
                    Map<String, Object> orderResult = JDServiceUtils.getOrderDetail(token, shippingItem.getSubTranSn());
                    orderApplyMap.put("invoice_price", orderResult.get("orderPrice"));
                    orderApplyMap.put("markId", "");
                    orderApplyMap.put("supplier_id", supplierId);
                    orderApplyMap.put("enterprise_id", enterpriseId);
                    MarketOrderApply marketOrderApply = marketOrderApplyService.saveMarketOrderApply(orderApplyMap);
                    Map<String, Object> shippingItemMap = new HashMap<String, Object>();
                    shippingItemMap.put("subTranSn", shippingItem.getSubTranSn());
                    List<ShippingItem> shippingItemList = shippingItemService.selectList(shippingItemMap);
                    for (ShippingItem si : shippingItemList) {
                        Map<String, Object> orderApplyItemMap = new HashMap<String, Object>();
                        orderApplyItemMap.put("order_apply_id", marketOrderApply.getId());
                        orderApplyItemMap.put("cost", si.getCost());
                        orderApplyItemMap.put("name", si.getName());
                        orderApplyItemMap.put("price", si.getPrice());
                        orderApplyItemMap.put("quantity", si.getQuantity());
                        orderApplyItemMap.put("sn", si.getSn());
                        orderApplyItemMap.put("spec", si.getSpec());
                        orderApplyItemMap.put("unit", si.getUnit());
                        orderApplyItemMap.put("thumbnail", si.getThumbnail());
                        orderApplyItemMap.put("product_id", si.getProductId());
                        orderApplyItemMap.put("enterprise_id", enterpriseId);
                        marketOrderApplyItemService.saveMarketOrderApplyItem(orderApplyItemMap);
                    }
                }
            }

            // end

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }

    }
}
